package com.hmdp.common.lock.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.common.lock.ILock;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: 公众号/B站：是叶十三
 * @Date: 2022/11/18
 * @Description: com.hmdp.common.lock.impl
 * @version: 1.0
 */
public class UUIDRedisLock implements ILock {

    private RedisTemplate redisTemplate;

    public static final String KEY_PREFIX = "lock:";


    // 引入uuid 防止锁被误删
    // true 去掉uuid里的横线
    public static final String UUID_PREFIX = UUID.randomUUID().toString(true) + "-";


    private String name;

    public UUIDRedisLock(String name, RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //  获取当前线程标识
        String threadId = Thread.currentThread().getId() + UUID_PREFIX;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name , threadId + "", timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        // 获取线程标识
        String threadId = Thread.currentThread().getId() + UUID_PREFIX;
        // 获取redis锁种的标识
        String redisKey = KEY_PREFIX + name;
        String id = (String)redisTemplate.opsForValue().get(redisKey);
        if (id.equals(threadId)){
            redisTemplate.delete(KEY_PREFIX + name);
        }
    }
}
